var config = require('../config/config.js');
var util = require('./util.js');

// 用户信息存储在App对象中。
// app.user -> userInfo
// app.
// 初次进入APP, APP Lauch时检查用户登录状态，并获取用户信息。

/**
 * 检测登录状态
 * @param callBack Function
 */
function checkSession(cb) {
    wx.checkSession({
        success: function (res) {
            let seesionId = util.getSessionId();
            if (!seesionId) {
                userLogin()
                    .then(cb);
            } else {
                cb && cb();
            }
        },
        fail: function (res) {
            userLogin()
                .then(cb);
        },
    })
}

/**
 * 将登录信息保存到全局。
 */
function saveLoginInfo(info) {
    let app = getApp();
    app.globalData.loginInfo = {
        code: info.code
    };
}

/**
 * 微信登录
 */
function wxLogin() {
    return new Promise((resolve, reject) => {
        wx.login({
            success: function (res) {
                console.log(res);
                saveLoginInfo(res);
                resolve(res);
            },
            fail: function (res) {
                reject(res);
            }
        });
    })

}

/**
 * 用户登录。
 * 首先微信登录，获取code，使用code从后端
 * 取回sessionID并存储。
 */
function userLogin() {
    return wxLogin()
        .then(requestLogin)
        .then(res => {
            return res;
        })
}

function requestLogin() {
    return new Promise((resolve, reject) => {
        let app = getApp();
        let code = app.globalData.loginInfo.code;
        let reqUserObj = {
            url: config.domain.requestDomain + config.service.userLogin,
            header: {'content-type': 'application/x-www-form-urlencoded'},
            method: "POST",
            data: {
                jsCode: code,
                userSource: config.userSource,
                systemInfo: JSON.stringify(util.getSystemInfo())
            },
            success: function (res) {
                // 登录成功,得到SessionId,存储sessionID
                if (res.data.code == 0) {
                    let sessionId = res.data.data.cSessionId;
                    wx.setStorageSync(config.storage.keySessionId, sessionId);
                    resolve(res);
                } else {
                    reject(res);
                }
            },
            fail: function (res) {
                reject(res);
            },
            complete: function (res) {
                console.log("User-userLogin", res);
            },
        };
        wx.request(reqUserObj);
    })
}

/**
 * 获取用户信息。
 * 弹出授权页面,该接口不会出现加密信息。
 */
function getUserInfo() {
    let app = getApp();
    return new Promise((resolve, reject) => {
        wx.getUserInfo({
            withCredentials: false,
            success: function (res) {
                // Storage the user info
                wx.setStorageSync({
                    key: config.storage.keyUserInfo,
                    data: res
                });
                app.globalData.user = res;
                resolve(res);
            },
            fail: function (res) {
                reject(res);
            },
            complete: function (res) {
                console.log("User-getUserInfo", res);
            }
        })
    })
}

function saveUserInfo(userInfo) {
    return new Promise((resolve, reject) => {
        let reqUserObj = {
            url: config.domain.requestDomain + config.service.saveWxUserInfo,
            header: {'content-type': 'application/x-www-form-urlencoded'},
            method: "POST",
            data: {
                ...userInfo,
                wxVersion: config.version,
                userSource: config.userSource,
                cSessionId: util.getSessionId()
            },
            complete: function () {
                resolve();
            }
        };
        wx.request(reqUserObj);
    })
}


/**
 * 获取用户信息。
 */
function getThirdUserInfo() {
    return new Promise((resolve, reject) => {
        let reqUserObj = {
            url: config.domain.requestDomain + config.service.userInfo,
            header: {'content-type': 'application/x-www-form-urlencoded'},
            method: "POST",
            data: {
                cSessionId: util.getSessionId()
            },
            complete: function (res) {
                resolve(res);
            }
        };
        wx.request(reqUserObj);
    })
}

module.exports = {
    checkSession: checkSession,
    userLogin: userLogin,
    getUserInfo: getUserInfo,
    saveUserInfo: saveUserInfo,
    getThirdUserInfo: getThirdUserInfo
};